package com.gexada.simplechat.websocket;

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import com.gexada.simplechat.data.ActiveWebSocketUser;
import com.gexada.simplechat.data.ActiveWebSocketUserRepository;

import java.util.Arrays;

public class WebSocketDisconnectHandler implements
		ApplicationListener<SessionDisconnectEvent> {
	private ActiveWebSocketUserRepository repository;
	private SimpMessageSendingOperations messagingTemplate;

	public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate,
			ActiveWebSocketUserRepository repository) {
		super();
		this.messagingTemplate = messagingTemplate;
		this.repository = repository;
	}

	public void onApplicationEvent(SessionDisconnectEvent event) {
		String id = event.getSessionId();
		if (id == null) {
			return;
		}
		ActiveWebSocketUser user = repository.findOne(id);
		if (user == null) {
			return;
		}

		repository.delete(id);

		messagingTemplate.convertAndSend("/topic/users/signout",
				Arrays.asList(user.getUsername()));
	}

}
